<?php

namespace front\modules\web\controllers;

use EasyWeChat\Foundation\Application;
use GuzzleHttp\Client;
use order\services\OrderUserService;
use users\models\CustomerInfo;
use users\services\RegionService;
use users\services\SmsService;
use users\services\UserService;
use wechat\models\Account;
use wechat\services\AccountService;
use Yii;
use yii\data\ActiveDataProvider;
use front\controllers\WebBaseController;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
/**
 * UserController implements the CRUD actions for UserModel model.
 */
class UserController extends WebBaseController
{
    public $layout = false;
    public $enableCsrfValidation = false;
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }


    /**
     * 注册并登陆
     * @param mobile
     * @param password
     * @return bool
     */
    public function actionLogin()
    {
        $session = \yii::$app->session;
        if (empty($session->get('openId'))) {
            $conf = AccountService::getWechatConfig(self::ORIGINAL_ID);
            $app = new Application($conf);
            $oauth = $app->oauth;
            Yii::$app->session->set('target_url', '/web/user/login');
            $oauth->redirect()->send();
        }
        $res = UserService::loginByOpenId($session->get('openId'));
        if($res){
            $session->set('user_id', UserService::getUserId());
            yii::info('BindingUrl test');
            if($session->has('bindingUrl')){
                $url = $session->get('bindingUrl');
                yii::info($url);
                $session->remove('bindingUrl');
                $session->remove('bindingUrl');
                return $this->redirect($url);
            }
            return $this->redirect(Yii::$app->user->getReturnUrl());
        }
        $data = yii::$app->request->get();
        if(yii::$app->request->isAjax) {
            $session = yii::$app->session;
            $mobile = $session -> get('mobile');
            if($data['mobile'] != $mobile){
                return '请确保发送验证码的手机与登录手机一致';
            }
            $valcode = $session -> get('valcode');
            if ($data['code'] == $valcode) {
                $openId = $_SESSION['openId'];
                $param = [
                    'mobile' => $session -> get('mobile'),
                    'openid' => $openId,
                    'unionid' => $session -> get('unionid')
                ];
                $register = UserService::registerCustomer($param);
                yii::info($register);
                if ($register['code'] == 0) {
                    if(yii::$app->user->isGuest){
                        return $register['message'];
                    }
                    $session->set('user_id', UserService::getUserId());
                    return 1;
                }
                return $register['message'];
            }
            return '验证码错误';
        }
        return $this->render('login');
    }



    /**
     *  发送验证码
     * @param $mobile
     * @return bool|string
     */
    public function actionSend()
    {
        $mobile = \yii::$app->request->get('phone');
        $valcode = SmsService::sendSMS($mobile);
        if($valcode){
            $session = yii::$app->session;
            $session -> set('valcode', $valcode);
            $session -> set('mobile', $mobile);
        }
        return 1;
    }



    /**
     * 获取用户信息
     */
    function actionIndex(){
        $data = yii::$app->request->get();
        $data['user_id'] = $this->getUserId();
        $info = UserService::getUserInfo($data['user_id'], 1);
        $userInfo['user'] = ArrayHelper::toArray($info['result']);
        $data['getByWeb'] = 1;
        $data['default'] = 1;
        $address = OrderUserService::search($data);
        $userInfo['address']['detail'] = '';
        if($address['code'] == 0){
            $address = ArrayHelper::toArray($address['result']);
            if(!empty($address)) {
                $address = $address[0];
                $district = RegionService::getAddress($address['district']);
                $userInfo['address']['detail'] = $district . $address['address'];
                $userInfo['address']['id'] = $address['id'];
            }
        }else{
            $userInfo['address'] = [];
        }
        $userInfo['photo'] = $this->photo;
        return $this->render('index',['data'=>$userInfo]);
    }


    /**
     *  user update info
     *
     * @return array
     */
    public function actionUpdate()
    {
        if (Yii::$app->request->isAjax) {
            $param = Yii::$app->request->get();
            $param['getByWeb'] = 1;
            if(isset($param['email'])){
                $param['email'] = strtolower($param['email']);
            }
            if(isset($param['nickname'])){
                $nickname = trim($param['nickname']);
                yii::info('test');
                yii::info($nickname);
                yii::info(strlen($nickname));
                if(strlen($nickname)<2){
                    return '昵称的长度必须大于2个字符';
                }
            }
            $info =  UserService::updateUserInfo($param);
            if($info['code'] == 0){
                return 1;
            } else {
                return $info['message'];
            }
        }else {
            return $this->render('update');
        }
    }

    public function actionDefaultAddress()
    {
        $data = yii::$app->request->get();
        $data['getByWeb'] = 1;
        $address = OrderUserService::search($data);
        if($address['code'] == 0){
            $address = ArrayHelper::toArray($address['result']);
            $address = $address[0];
            $district = RegionService::getAddress($address['district']);
            $userInfo['address']['detail'] = $district . $address['address'];
        }else{
            $userInfo['address'] = [];
        }
    }

    public function actionBinding()
    {
        $data = Yii::$app->request->get();
//        $data['id'] = $user_id;
        $result = UserService::binding($data);
        return json_encode($result);

    }


    public function actionUsertag()
    {
        if(isset($_GET['openid'])){
            $openId = $_GET['openid'];
            $useConfig = Account::getWechatConfigbyAid(7);
            yii::info($useConfig);
            $app = new Application($useConfig);
            $tag = $app->user_tag;
            $openIdList = [$openId];
            return $tag->batchTagUsers($openIdList, 102);
        }
    }

}
